<template>
  <view class="initiateGroupChat">
    <topTitle :title="title">
      <template #right>
        <view class="save" @tap="confirm" :class="{ confirm: activeCount }"
          >确认</view
        >
      </template>
    </topTitle>
    <view class="add">
      <view>已选人员（{{ activeCount }}）</view>
      <view>
        <view v-if="activeCount">
          <up-avatar
            v-for="(item, idx) in friendList"
            v-show="item.active"
            :key="idx"
            class="avatar"
            mode="aspectFill"
            :src="item.picture"
            size="40"
          ></up-avatar>
        </view>
        <view v-else> <i></i> +请添加</view>
      </view>
    </view>
    <view class="friendList">
      <view>{{ type == 3 ? "全部成员" : "全部好友" }}</view>
      <view class="addList">
        <view
          v-for="(item, idx) in friendList"
          :key="idx"
          @tap="item.active = !item.active"
          :class="{ active: item.active, disabled: item.disabled }"
        >
          <up-avatar
            class="avatar"
            mode="aspectFill"
            :src="item.picture"
            size="50"
          ></up-avatar>
          <text> {{ item.notes || item.nick_name }}</text>
        </view>
      </view>
    </view>
    <canvas
      canvas-id="groupAvatarCanvas"
      style="width: 200px; height: 200px"
    ></canvas>

    <up-modal
      :show="groupNameShow"
      confirmText="创建"
      cancelText="取消"
      title="群聊名称"
      :showCancelButton="true"
      @cancel="groupNameShow = false"
      @confirm="GroupCreateFn"
    >
      <up-input
        placeholder="請輸入群聊名称"
        border="surround"
        focus
        v-model="group_name"
      ></up-input>
    </up-modal>
  </view>
</template>
<script setup lang="ts">
import { ref, computed, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { Friend, GroupCreate, GroupInfo, GroupUpdate } from "@/api/ImApi";

let type = ref<number | string>();
let group_id = ref<number | string>();
let title = ref<string>();

let member = ref<any>([]);
onLoad((option: any) => {
  type.value = option.type;
  if (option.type == 1) {
    title.value = "发起群聊";
    FriendFn();
  } else {
    group_id.value = option.group_id;
    const query = decodeURIComponent(option.member);
    if (query) {
      member.value = JSON.parse(query);
    }
  }
  if (option.type == 2) {
    title.value = "添加成员";
    FriendFn();
  }
  if (option.type == 3) {
    title.value = "删除成员";
    friendList.value = member.value;
  }
});
// 加载好友列表
let friendList = ref<any>([]);
const instance = getCurrentInstance()?.appContext.config.globalProperties;
const FriendFn = async () => {
  friendList.value = await instance?.$db.loadData("friendList", {
    sortField: "id",
  });
  if (type.value != 1) {
    activeList();
  }
  let res = await Friend();
  friendList.value = res.list;
  if (type.value != 1) {
    activeList();
  }
};
// 判断已经选中或者禁止
const activeList = async () => {
  console.log(friendList.value);
  console.log(member.value);
  if (type.value == 2) {
    friendList.value = friendList.value.map((friend: any) => {
      const matchedMember = member.value.find(
        (memberItem: any) => memberItem.user_id === friend.user_id
      );
      if (matchedMember) {
        friend.active = true;
        friend.disabled = true;
      }

      return friend; // 返回更新后的 friend
    });
  }
};

// 计算active为true的数量
const activeCount = computed(() => {
  return friendList.value?.filter((item: any) => item.active).length ?? 0;
});

// 创建群聊并添加名称
let groupNameShow = ref<boolean>(false);
let group_name = ref<string>();
const confirm = async () => {
  if (type.value == 1) {
    if (activeCount.value <= 1) {
      uni.showToast({ title: "至少选中2个好友才能创建群聊", icon: "none" });
      return;
    }
    groupNameShow.value = true;
  } else {
    const user = friendList.value
      .filter((friend: any) => friend.active && !friend.disabled)
      .map((friend: any) => friend.user_id);

    if (!user.length) {
      uni.showToast({ title: "请选择成员", icon: "none" });
      return;
    }
    await GroupUpdate({
      group_id: group_id.value,
      member: {
        operation: type.value == 2 ? 1 : 2,
        user,
      },
    });
    instance?.goBack(1, type.value == 2 ? "添加成功" : "删除成功");
  }
};

const GroupCreateFn = async () => {
  if (!group_name.value) {
    uni.showToast({ title: "请输入群聊名称", icon: "none" });
    return;
  }

  const member = friendList.value
    .filter((item: any) => item.active)
    .map((item: any) => item.user_id);

  let res = await GroupCreate({ group_name: group_name.value, member });
  let info = await GroupInfo({ group_id: res.group_id });

  uni.showToast({ title: "创建成功", icon: "none" });

  instance?.goRedirectTo(
    "/pages/chat/chat?group_id=" +
      res.group_id +
      "&createGroupChat=1" +
      "&item=" +
      encodeURIComponent(JSON.stringify(info)),
    "创建成功"
  );

  groupNameShow.value = false;
  group_name.value = "";
};
</script>

<style scoped lang="scss">
@import "../../static/scss/group.scss";
</style>
